package com.seven.springboot.enums;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 带有索引值的枚举
 * 
 * @author yinbenyang
 * @date 2018年7月3日下午12:00:43
 */
public interface IndexedEnum {

	/**
	 * 获取该枚举的索引值
	 * 
	 * @return 返回>=0的索引值
	 */
	int getIndex();

	String getMessage();

	public static class IndexedEnumUtil {

		public static final Logger LOGGER = LoggerFactory
				.getLogger(IndexedEnum.class);

		public static <E extends IndexedEnum> Map<Integer, E> toIndexMap(
				E[] enums) {
			if(enums == null || enums.length <= 0) {
				throw new IllegalArgumentException("enums must not be empty");
			}
			Map<Integer, E> enumMap = new HashMap<Integer, E>(enums.length);
			for (E e : enums) {
				
				int index = e.getIndex();
				if (enumMap.containsKey(index)) {
					throw new IllegalArgumentException("枚举中有重复的index, index="
							+ index + ", type= "
							+ e.getClass().getComponentType().getName());
				}
				enumMap.put(index, e);
			}
			return enumMap;
		}

		public static <E extends IndexedEnum> Map<String, E> toMessageMap(
				E[] enums) {
			if(enums == null || enums.length <= 0) {
				throw new IllegalArgumentException("enums must not be empty");
			}
			Map<String, E> enumMap = new HashMap<String, E>(enums.length);
			for (E e : enums) {
				String message = e.getMessage();
				if (enumMap.containsKey(message)) {
					throw new IllegalArgumentException(
							"枚举中有重复的message, message="
									+ message
									+ ", type= "
									+ e.getClass().getComponentType()
											.getName());
				}
				enumMap.put(message, e);
			}
			return enumMap;
		}

		public static <E extends IndexedEnum> int getMaxIndex(E[] enums) {
			if(enums == null || enums.length <= 0) {
				throw new IllegalArgumentException("enums must not be empty");
			}
			int tempIndex = 0;
			for (E e : enums) {
				int index =  e.getIndex();
				if (index > tempIndex) {
					tempIndex = index;
				}
			}
			return tempIndex;
		}
	}
}